package com.kunbo.cn.controller.core.purchase;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.kunbo.cn.entity.core.approval.TareExceptionApproval;
import com.kunbo.cn.entity.core.error.CarAbnormal;
import com.kunbo.cn.entity.core.error.ExceptionBean;
import com.kunbo.cn.entity.core.poundlist.PurchasePoundList;
import com.kunbo.cn.entity.core.poundlist.SalesPoundList;
import com.kunbo.cn.entity.system.user.User;
import com.kunbo.cn.enumeration.core.logistics.CarError;
import com.kunbo.cn.enumeration.core.poundlist.PoundListState;
import com.kunbo.cn.service.core.approval.TareExceptionApprovalService;
import com.kunbo.cn.service.core.card.IssuanceCardService;
import com.kunbo.cn.service.core.error.CarAbnormalService;
import com.kunbo.cn.service.core.poundlist.PurchasePoundListService;
import com.kunbo.cn.service.core.poundlist.SalesPoundListService;
import com.kunbo.cn.util.retu.CommonResult;
/**
 * <p>Title: PurchaseNoticeController</p>
 * <p>Description:根据身份证号获取采购或者销售通知单 </p>
 * <p>Company: www.kunbo.cn</p> 
 * @author	yang'f
 * @date	2019年4月15日下午6:18:24
 * @version 1.0
 */
@RestController
@RequestMapping("/pnc/")
public class PurchaseNoticeController {
	@Autowired
	private JdbcTemplate jdbc;
	
	@Autowired
	private PurchasePoundListService ppls;
	
	@Autowired
	private SalesPoundListService spls;
	
	@Autowired
	private TareExceptionApprovalService teaService;
	
	@Autowired
	private CarAbnormalService caService;
	@Autowired
	private IssuanceCardService icCardService;
	//根据身份证号获取对应的通知单
	@RequestMapping(value="getNoticeOrderByIdCard",method=RequestMethod.POST)
	@Transactional
	public CommonResult getNoticeOrder(String idCard,Double weight,HttpSession session) {
		if(StringUtils.isBlank(idCard)) {
			ExceptionBean error = new ExceptionBean();
			error.setSpeakMsg("IC卡无效，请联系管理员");
			error.setScreenLine1("");
			error.setScreenLine2("");
			return new CommonResult(false,"",error);
		}
		System.out.println(idCard);
		//根据卡编码获取对应的身份证信息
		String idNumber  = "";
		List<Map<String,Object>> cardList = icCardService.findByIdCardNumber(idCard);
		if(cardList.size()>0) {
			idNumber = cardList.get(0).get("id_card").toString();
		}
		String pnSql = "select * from business_notice_of_arrival "
				+ "where card_id = '"+idNumber+"' AND notice_state = '7'  LIMIT 1";
		String snSql = "select * from 	business_delivery_notice_manage "
				+ "where id_number = '"+idNumber+"' and state = '7' LIMIT 1";
		System.out.println(pnSql+"采购通知单sql");
		System.out.println(snSql+"销售通知单sql");
		List<Map<String,Object>> pnList = jdbc.queryForList(pnSql);
		List<Map<String,Object>> snList = jdbc.queryForList(snSql);
		if(pnList.size()>0) {
			return new CommonResult(true,"获取成功",pnList.get(0));
		}else if(snList.size()>0){
			//1.当获取到提货通知单信息时，判断皮重是否异常
			Map<String,Object> sNotice = snList.get(0);
			//2.获取车牌信息
			String plateNumber = sNotice.get("train_number").toString();
			
			//3.获取最近三次车辆皮重信息
			String tareSql = " select round(AVG(tare),2) as avgTare from db_business_sales_pound_list where wagon_number = '"+plateNumber+"' AND "
					+ " state = '2' ORDER BY create_time DESC limit 3 ";
			Map<String,Object> avgObj = jdbc.queryForMap(tareSql);
			//4.获取通知单当前的状态（1.如果未校验则进行校验2.如果已经进行了校验则看看是否有需要审批的异常记录）
			//5.根据车牌号和状态获取是否有未审批的数据
			String excSql = "select id,exception_value from business_tare_exception_approval_manage where car_number = '"+plateNumber+"' and state = '0' ";
			if(sNotice.get("check_state").toString().equals("0")) {
				if(null!=avgObj.get("avgTare")) {
					BigDecimal avgWeight = new BigDecimal(avgObj.get("avgTare").toString());
					BigDecimal currentWeight = new BigDecimal(Double.toString(weight));
					Double b = currentWeight.subtract(avgWeight).doubleValue();
					TareExceptionApproval tea = new TareExceptionApproval();
					if(b>0.5 || b<-0.5) {
						tea.setType("销售");
						tea.setState("0");
						tea.setCar_number(plateNumber);
						tea.setTare(Double.toString(weight));
						tea.setAverage_tare(avgObj.get("avgTare").toString());
						tea.setOrder_number(sNotice.get("order_code").toString());
						tea.setNotice_number(sNotice.get("notice_code").toString());
						tea.setMaterial(sNotice.get("material").toString());
						tea.setExceptionValue(b);
						teaService.save(tea);;
						//同时更新对应的通知单状态
						jdbc.update("update business_delivery_notice_manage set check_state = '1' where id ="+Integer.parseInt(String.valueOf(sNotice.get("id")))+" ");
						ExceptionBean error = new ExceptionBean();
						error.setSpeakMsg("车辆皮重异常，需要审批");
						error.setScreenLine1("皮重异常");
						error.setScreenLine2("值："+b+"吨");
						return new CommonResult(false,"",error);
					}else {
						return new CommonResult(true,"获取成功",snList.get(0));
					}

				}else {
					return new CommonResult(true,"获取成功",snList.get(0));
				}
			}else if(sNotice.get("check_state").toString().equals("1")) {
				List<Map<String,Object>> list = jdbc.queryForList(excSql);
				if(list.size()>0) {
					ExceptionBean error = new ExceptionBean();
					error.setSpeakMsg("车辆皮重异常，需要审批");
					error.setScreenLine1("皮重异常");
					error.setScreenLine2("值："+list.get(0).get("exception_value").toString()+"");
					return new CommonResult(false,"",error);
				}else {
					return new CommonResult(true,"获取成功",snList.get(0));
				}
			}
			return new CommonResult(true,"获取成功",snList.get(0));
			
		}else {
			ExceptionBean error = new ExceptionBean();
			error.setSpeakMsg("对不起，您没有对应的派车单");
			error.setScreenLine1("");
			error.setScreenLine2("");
			return new CommonResult(false,"",error);
		}
		
		
	}
	
	//二次过磅，根据身份证号获取首次记录的磅单信息//192.168.2.101
	@RequestMapping(value="getFirstPoundList",method=RequestMethod.POST)
	public CommonResult getFirstPoundList(String idCard,Double weight) {
		//CommonResult result = new CommonResult();
		if(StringUtils.isBlank(idCard)) {
			return new CommonResult(false,"IC卡无效，请联系磅房管理员",null);
		}
		System.out.println("当前卡号为："+idCard);
		String idNumber  = "";
		List<Map<String,Object>> cardList = icCardService.findByIdCardNumber(idCard);
		if(cardList.size()>0) {
			idNumber = cardList.get(0).get("id_card").toString();
		}
		PurchasePoundList ppl = ppls.findByIDNumber(idNumber,PoundListState.firstWeigh);
		SalesPoundList spl = spls.findByIdCard(idNumber,PoundListState.firstWeigh);
		if(null!=ppl) {
			//1.获取车牌号
			String carNumber = ppl.getWagonNumber();
			//2.根据车牌号获取平均值
			String tareSql = " select round(AVG(tare),2) as avgTare from db_business_purchase_pound_list where wagon_number = '"+carNumber+"' AND "
					+ " state = '2' ORDER BY create_time DESC limit 3 ";
			String excSql = "select id,exception_value from business_tare_exception_approval_manage where car_number = '"+carNumber+"' and state = '0' ";
			Map<String,Object> avgObj = jdbc.queryForMap(tareSql);
			//3.当前称重和平均值对比
			String dhSql = "select check_state from business_notice_of_arrival "
					+ "where notification_code ='"+ppl.getArrivalOfGoodsNumber()+"' ";
			List<Map<String,Object>> listDhNotice = jdbc.queryForList(dhSql);
			String noticeState = "";
			if(listDhNotice.size()>0) {
				noticeState+=listDhNotice.get(0).get("check_state").toString();
			}
			if(noticeState.equals("0")) {
				if(null!=avgObj.get("avgTare")) {
					BigDecimal avgWeight = new BigDecimal(avgObj.get("avgTare").toString());
					BigDecimal currentWeight = new BigDecimal(Double.toString(weight));
					Double b = currentWeight.subtract(avgWeight).doubleValue();
					TareExceptionApproval tea = new TareExceptionApproval();
					if(b>0.5 || b<-0.5) {
						tea.setType("销售");
						tea.setState("0");
						tea.setCar_number(carNumber);
						tea.setTare(Double.toString(weight));
						tea.setAverage_tare(avgObj.get("avgTare").toString());
						tea.setOrder_number(ppl.getCgOrderNumber());
						tea.setNotice_number(ppl.getArrivalOfGoodsNumber());
						tea.setMaterial(ppl.getMateriel());
						tea.setExceptionValue(b);
						teaService.save(tea);;
						//同时更新对应的通知单状为已校验
						jdbc.update("update business_notice_of_arrival set check_state = '1' where notification_code ='"+ppl.getArrivalOfGoodsNumber()+"' ");
						ExceptionBean error = new ExceptionBean();
						error.setSpeakMsg("车辆皮重异常，需要审批");
						error.setScreenLine1("皮重异常");
						error.setScreenLine2("值："+b+"");
						return new CommonResult(false,"",error);
					}else {
						return new CommonResult(true,"获取成功",ppl);
					}

				}else {
					return new CommonResult(true,"获取成功",ppl);
				}
				
			}else if(noticeState.equals("1")) {
				List<Map<String,Object>> list = jdbc.queryForList(excSql);
				if(list.size()>0) {
					ExceptionBean error = new ExceptionBean();
					error.setSpeakMsg("车辆皮重异常，需要审批");
					error.setScreenLine1("皮重异常");
					error.setScreenLine2("值："+list.get(0).get("exception_value").toString()+"");
					return new CommonResult(false,"",error);
				}else {
					return new CommonResult(true,"获取成功",ppl);
				}
			}
			//4.如果异常则给出提示，不异常则返回数据
			
		}else if(null!=spl){
			//1.获取车牌号
			String carNumber = spl.getWagonNumber();
			//2.根据车牌号获取最大载重
			String carSql = " select maximum_payload from 	vehicle_management where license_plate_number = '"+carNumber+"' ";
			List<Map<String,Object>> list = jdbc.queryForList(carSql);
			Double maxLoad = 0.00;
			if(list.size()>0) {
				maxLoad = Double.valueOf(list.get(0).get("maximum_payload").toString());
			}
			BigDecimal load = new BigDecimal(list.get(0).get("maximum_payload").toString());
			BigDecimal currentWeight = new BigDecimal(Double.toString(weight));
			if(weight>maxLoad) {
				ExceptionBean error = new ExceptionBean();
				error.setSpeakMsg("超限，需要处理");
				error.setScreenLine1("核"+maxLoad+"");
				error.setScreenLine2("实"+weight+"超："+currentWeight.subtract(load).doubleValue()+"");
				return new CommonResult(false,"",error);
			}else {
				return new CommonResult(true,"获取成功",spl);
			}
		}else {
			ExceptionBean error = new ExceptionBean();
			error.setSpeakMsg("对不起，没有首次磅单记录");
			error.setScreenLine1("");
			error.setScreenLine2("");
			return new CommonResult(false,"",error);
		}
		
		return null;
		
	}

}
